package com.uxwine.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedAction;

public class ClassReflect {
	public static final String TAG = ClassReflect.class.getName();

	public static Class<?> classForName(String className) {
		try {
			return Class.forName(className);
		} catch (ClassNotFoundException e) {
			ClassLoader clsLoader = Thread.currentThread()
					.getContextClassLoader();
			try {
				return Class.forName(className, false, clsLoader);
			} catch (ClassNotFoundException cnfe) {
				return null;
			}
		}
	}

	public static Field getAccessibleField(Class<?> cls, String fieldName) {
		Field field = null;
		if ((cls == null) || (fieldName == null) || (fieldName.trim().length() == 0))
			return field;
		
		Class<?> pCls = cls;
		while (true) {
			try {
				field = pCls.getDeclaredField(fieldName);
				break;
			} catch (NoSuchFieldException e) {
				pCls = cls.getSuperclass();
				if(null == pCls)
					break;
			}
		}
//		if(field != null && !field.isAccessible())
//		{
//			AccessController.doPrivileged(new PrivilegedAction()
//			 {
//				 public Object run()
//				 {
//					 ClassReflect.this.setAccessible(true);
//					 return null;
//				 }
//			 });
//		}
		return field;		
	}
	
	public static Field getAccessibleField(String className, String fieldName) {
		return getAccessibleField(ClassReflect.classForName(className), fieldName);
	}
	
	public static Object getStaticFieldValue(Field field)
	{
		try {
			return field.get(null);
		} catch (Throwable thr) {
			Log.e(TAG, thr.getMessage() + "");
		}
		return null;
	}
	
	public static Object getStaticFieldValue(String className, String fieldName) {
		return getStaticFieldValue(getAccessibleField(ClassReflect.classForName(className), fieldName));
	}

}
